<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'workNumber', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <img :src="scope.row.staffPhoto" style="width:100%;height:100%">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <div style="height: 60px; margin-top: 10px">
            <!-- 分页 -->
            <el-pagination
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :page-sizes="[2,5,10,20]"
              @current-change="hCurrentChange"
              @size-change="hSizeChange"
            />
          </div>
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <addorEdit ref="addEmployees" @close="showDialog=false" @success="hUpdateEmpolyee" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
// const hireType = {}
// EmployeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
import addorEdit from './empDialog'
export default {
  name: 'Employees1',
  components: {
    addorEdit
  },
  data() {
    return {
      showDialog: false,
      list: [],
      page: 1,
      size: 10,
      total: 0
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (!one) return // 没数据就直接不执行
      const header = Object.keys(one).map(enKey => {
        return map[enKey]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      return { header: header, data: data }
    },
    async handleDownload() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res.data.rows)
        const { header, data } = this.formatData(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
        // excel 指的是模块对象，可以使用excel调用 Export2Excel文件中的函数或者使用Export2Excel文件中的变量
          excel.export_json_to_excel({
            header: header,
            data: data,
            filename: this.filename, // 文件名
            autoWidth: this.autoWidth, // 自动适配宽度
            bookType: this.bookType // 文件的类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log(res, 'xxxxxx')
        this.$message.success('删除成功')
        this.loadEmployeeList()
        // 保存数据
      } catch (error) {
        console.log(error)
      }
    },
    hDel(id) {
      this.$confirm('此操作将删除该角色, 是否继续?').then(() => {
        this.doDel(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hSizeChange(val) {
      console.log(`每页${val}条`)
      this.size = val
      this.loadEmployeeList()
    },
    hCurrentChange(val) {
      console.log(`第${val}页`)
      this.page = val
      this.loadEmployeeList()
    },
    formOfEmploymentFormat(data) {
      return hireType[data] || '未知'
    },
    async loadEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      console.log(res, '团购列表')
      this.list = res.data.rows
      this.total = res.data.total
    },
    hResetForm() {
      this.$refs.addEmployees.resetform()
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.page = Math.ceil(this.total / this.size)
      this.loadEmployeeList()
    }
  }

}
</script>
